<?php

require "../utility.php";
require "../types.php";

$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);

http_response_code(403);

if ($user_id !== null) {
    $order_query_str = "SELECT ID, orderTime, status, address FROM Orders WHERE userID = $user_id ORDER BY orderTime DESC;";
    $order_query = $conn->query($order_query_str);

    $orders = [];
    while ($data = $order_query->fetch_row()) {
        $order = Order::fromArray($data);
        $book_query_str = "SELECT bookID, cnt FROM OrderBooks WHERE orderID = '$order->id'";
        $book_query = $conn->query($book_query_str);
        while ($book_data = $book_query->fetch_row()) {
            $book = OrderBook::fromArray($book_data);
            $order->addBook($book);
        }

        $orders[] = $order;
    }

    http_response_code(200);
    header("Content-Type: application/json");
    echo json_encode($orders, JSON_UNESCAPED_UNICODE);
}

?>